package com.woniuxy.three.pms.user.controller;

import javax.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.three.pms.util.QiniuFileUploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.woniuxy.three.pms.bean.UserBean;
import com.woniuxy.three.pms.sms.CheckSmsResult;
import com.woniuxy.three.pms.user.service.IUserService;
import com.woniuxy.three.pms.util.CacheUtil;
import com.woniuxy.three.pms.util.Msg;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import java.io.IOException;


/**
 * 
 * @ProjectName:Pms
 * @Date:2019年6月18日
 * @ClassName:UserController.java
 * @Author:ThinkPad
 * @Description:TODO 用户控制器模块测试
 * @Version:1.0
 * @See：参考版本
 *
 */

@Controller
@Slf4j
public class UserController {
	@Autowired
	private IUserService userService;
	
	@Autowired
	private CacheUtil cacheUtil;

	@Autowired
	private CheckSmsResult checkSmsResult;

	//注册
	@RequestMapping(value = "/user",method = RequestMethod.POST)
	@ResponseBody
	public Msg userRegister(@RequestBody UserBean user) {
		//盐值
		ByteSource mobileSalt = ByteSource.Util.bytes(user.getMobile());
		UserBean requestMobile = userService.findUserByMobile(user.getMobile());
		if (requestMobile!=null){
			return Msg.fail().add("error","您的手机号已经注册");
		}
		//加密后的密码
		Object enResult = new SimpleHash("MD5", user.getPassword(), mobileSalt, 1024);
		user.setPassword(enResult.toString());
		int addResult = userService.adduser(user);
		if (addResult > 0){
			return Msg.success();
		}
		return Msg.fail();
	}

	@ResponseBody
	@RequestMapping(value = "/user/checkUserUsed",method = RequestMethod.GET)
	public Msg checkUserIsUsed(String mobile){
		UserBean userByMobile = userService.findUserByMobile(mobile);
		if (userByMobile!=null){
			return Msg.fail().add("error","该手机号已经注册");
		}
		return Msg.success().add("info","该手机号可用");
	}

	//登录  验证码方式
	@RequestMapping(value="login/{mobile}/{verCode}",method=RequestMethod.GET)
	@ResponseBody
	public Msg userLoginByVerifyCode(@PathVariable("mobile")String mobile,@PathVariable("verCode")String verifyCode,HttpServletRequest request) {
		Subject currentUser = SecurityUtils.getSubject();
		if(!currentUser.isAuthenticated()){
			UsernamePasswordToken token = new UsernamePasswordToken(mobile,verifyCode);
			try{
				currentUser.login(token);
				//查询结果
				String result = cacheUtil.getValueWithKey("login_info_" + mobile);

				cacheUtil.delCacheWithKey("login_info_" + mobile);
				UserBean userBean = new ObjectMapper().readValue(result, UserBean.class);
				return Msg.success().add("user_info",userBean);
			}catch (UnknownAccountException uae){
				log.error("用户名异常");
				uae.printStackTrace();
			}catch (IncorrectCredentialsException ice) {
				log.error("密码异常");
				ice.printStackTrace();
			} catch (LockedAccountException lae) {
				log.error("被锁定异常");
				lae.printStackTrace();
			} catch (AuthenticationException e) {
				log.error("其他异常");
				e.printStackTrace();
			} catch (JsonParseException e) {
				log.error("JSON转换异常");
				e.printStackTrace();
			} catch (JsonMappingException e) {
				log.error("JSON映射Class异常");
				e.printStackTrace();
			} catch (IOException e) {
				log.error("其他IO异常");
				e.printStackTrace();
			}
		}

		/*
		try {
			UserBean loginResult = userService.login(mobile, verifyCode);
			if (loginResult != null) {
				return Msg.success().add("userLoginResult", loginResult);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return Msg.fail();
	}
	
	/**
	 * 通过用户名密码登录
	 * @param mobile
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/user/login",method = RequestMethod.POST)
	@ResponseBody
	public Msg userLoginByPassword(@RequestParam("mobile")String mobile,@RequestParam("password")String password) {
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(mobile, password);
			try {
				currentUser.login(token);
				String dbUserInfo = cacheUtil.getValueWithKey("login_info_"+mobile);
				cacheUtil.delCacheWithKey(mobile);
				ObjectMapper mapper = new ObjectMapper();
				UserBean userBean = mapper.readValue(dbUserInfo, UserBean.class);
				return Msg.success().add("userInfo", userBean);

			} catch (UnknownAccountException uae){
				log.error("用户名异常");
				uae.printStackTrace();
			}catch (IncorrectCredentialsException ice) {
				log.error("密码异常");
				ice.printStackTrace();
			} catch (LockedAccountException lae) {
				log.error("被锁定异常");
				lae.printStackTrace();
			} catch (AuthenticationException e) {
				log.error("其他异常");
				e.printStackTrace();
			} catch (JsonParseException e) {
				log.error("转换对象失败");  
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return Msg.fail();
	}
	
	//注销  使用shiro 的权限管理系统控制
	
		//注销  使用shiro 的权限管理系统控制

		//修改信息
		// 用户的修改信息，用户本身修改信息：
		@PostMapping("/user/modify")
		@ResponseBody
		public Msg userModifySelfInfo(@RequestBody UserBean user) {
			boolean modifyResult = userService.modifyUser(user);
			if (modifyResult){
				return Msg.success();
			}
			return Msg.fail();
		}
	
	//系统管理员修改会员的记录
	@PostMapping("/root/modifyUser")
	@ResponseBody
	public Msg rootModifyUserInfo(@RequestBody UserBean user) {
		boolean modifyResult = userService.rootModifyUser(user);
		if (modifyResult){
			return Msg.success();
		}
		return Msg.fail();
	}
	
	//查询用户信息模糊查询
	@RequestMapping(value = "/user/searchName",method=RequestMethod.GET)
	@ResponseBody
	public Msg findUserByKeyWord(String keyword) {
		PageInfo<UserBean> searchResult = userService.searchUserByKeyWord(keyword);
		return Msg.success().add("result", searchResult);
	}
	
	//查询用户信息 根据VIP查询
	@RequestMapping(value = "/user/searchVip",method=RequestMethod.GET)
	@ResponseBody
	public Msg findUserByVip(String vip) {
		PageInfo<UserBean> searchResult = userService.searchUserByVip(vip);
		return Msg.success().add("result", searchResult);
	}
	
	//查询用户信息 根据用户编号查询
	@RequestMapping(value = "/user/searchId",method=RequestMethod.GET)
	@ResponseBody
	public Msg finduserById(@RequestParam("id")Integer userId) {
		UserBean user = userService.finduserById(userId);
		return Msg.success().add("userInfo",user);
	}

	//用户上传头像
	// required=false表示不传的话，会给参数赋值为null，required=true就是必须要有
	@ResponseBody
	@RequestMapping(value = "/user/uploadHead",method = RequestMethod.POST)
	public Msg uploadHeadImg(HttpServletRequest request, @RequestParam(required = false)MultipartFile file,@RequestParam("mobile")String mobile) throws IOException {
		String headImg = userService.uploadHeadImg(file, mobile);
		if (StringUtils.isBlank(headImg)){
			return Msg.success().add("url",headImg);
		}
		return Msg.fail();
	}

	/***
	 * 测试多文件上传
	 * @param files
	 * @return
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadImages",method = RequestMethod.POST)
	public Msg uploadImages(@RequestParam("files") MultipartFile[] files){
		try {
			String uploadImages = QiniuFileUploadUtil.uploadImages(files);
				return Msg.success().add("fileUrls",uploadImages);
		} catch (IOException e) {
			log.error("文件转换异常");
			e.printStackTrace();
		}
		return Msg.fail();
	}




	@ResponseBody
	@GetMapping("/user/{pageNo}/{pageSize}")
	public PageInfo<UserBean> findall(@PathVariable("pageNo")Integer pageNo,@PathVariable("pageSize")Integer pageSize){
		System.out.println();
		return userService.findall(pageNo, pageSize);


	}
}
